#include <func.h>

int main(int argc,char *argv[])
{
    ARGS_CHECK(argc,3);
    int socketfd;
    socketfd=socket(AF_INET,SOCK_STREAM,0);
    ERROR_CHECK(socketfd,-1,"socket");
    printf("socketfd=%d\n",socketfd);
    struct sockaddr_in ser;
    bzero(&ser,sizeof(ser));
    ser.sin_family=AF_INET;
    ser.sin_addr.s_addr=inet_addr(argv[1]);
    ser.sin_port=htons(atoi(argv[2]));
    int ret;
    ret=bind(socketfd,(struct sockaddr*)&ser,sizeof(struct sockaddr));
    ERROR_CHECK(ret,-1,"bind");
    listen(socketfd,10);
    int newfd;
    struct sockaddr_in cli;
    bzero(&cli,sizeof(cli));
    socklen_t len=sizeof(cli);
    newfd=accept(socketfd,(struct sockaddr*)&cli,&len);
    ERROR_CHECK(newfd,-1,"accept");
    printf("client ip=%s,client port=%d\n",
           inet_ntoa(cli.sin_addr),ntohs(cli.sin_port));
    char buf[1024]={0};
    fd_set t;
    while(1)
    {
        FD_ZERO(&t);
        FD_SET(newfd,&t);
        FD_SET(STDIN_FILENO,&t);
        select(newfd+1,&t,NULL,NULL,NULL);
        if(FD_ISSET(newfd,&t))
        {
            bzero(buf,sizeof(buf));
            if(!recv(newfd,buf,sizeof(buf),0))
            {
                printf("GooBye!\n");
                break;
            }
            write(STDOUT_FILENO,buf,strlen(buf));
        }
        if(FD_ISSET(STDIN_FILENO,&t))
        {
            bzero(buf,sizeof(buf));
            read(STDIN_FILENO,buf,sizeof(buf));
            send(newfd,buf,sizeof(buf)-1,0);
        }
    }
    return 0;
}

